package cn.jfast.plugin.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import cn.jfast.plugin.util.StringUtils;

public class DbBase {
	
	protected String dbUrl;
	
	protected String dbUser;
	
	protected String dbPassword;
	
	protected static final ConcurrentMap<String, Table> tableStore = new ConcurrentHashMap<String, Table>();


	public Collection<Table> getTables() {
		return tableStore.values();
	}

	public void initData(String dbUrl, String dbUser, String dbPassword)
			throws SQLException {
		this.dbUrl = dbUrl;
		this.dbUser = dbUser;
		this.dbPassword = dbPassword;
		Connection conn = DriverManager
				.getConnection(dbUrl, dbUser, dbPassword);
		DatabaseMetaData meta = conn.getMetaData();
		ResultSet rs = meta.getTables(null, null, "%%",
				new String[] { "TABLE" });
		Table table;
		while (rs.next()) {
			table = new Table();
			table.setTableName(rs.getString("TABLE_NAME"));
			table.setNickName(StringUtils.firstCharToUpperCase(StringUtils
					.dbColumn2ModelColumn(rs.getString("TABLE_NAME"))));
			table.setType(rs.getString("TABLE_TYPE"));
			table.setRemarks(rs.getString("REMARKS"));
			ResultSet rc = meta.getColumns(null, null, table.getTableName(),
					"%%");
			Column column;
			while (rc.next()) {
				column = new Column();
				column.setName(rc.getString("COLUMN_NAME"));
				column.setDefaultValue(rc.getString("COLUMN_DEF"));
				column.setSize(rc.getInt("COLUMN_SIZE"));
				column.setType(rc.getInt("DATA_TYPE"));
				column.setNullAble(rc.getString("NULLABLE"));
				column.setRemarks(rc.getString("REMARKS"));
				table.addColumn(column);
			}
			ResultSet rp = meta
					.getPrimaryKeys(null, null, table.getTableName());
			while (rp.next()) {
				table.addPrimaryKey(StringUtils.dbColumn2ModelColumn(rp.getString("COLUMN_NAME")));
			}
			tableStore.put(table.getTableName(), table);
		}
	}

	public Table getTable(String tableName) {
		return tableStore.get(tableName);
	}

	public String getDbUrl() {
		return dbUrl;
	}

	public void setDbUrl(String dbUrl) {
		this.dbUrl = dbUrl;
	}

	public String getDbUser() {
		return dbUser;
	}

	public void setDbUser(String dbUser) {
		this.dbUser = dbUser;
	}

	public String getDbPassword() {
		return dbPassword;
	}

	public void setDbPassword(String dbPassword) {
		this.dbPassword = dbPassword;
	}
}
